package com.retoc.oawx.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.retoc.oawx.common.util.R;
import com.retoc.oawx.config.shiro.JWTUtil;
import com.retoc.oawx.domain.*;
import com.retoc.oawx.domain.req.ApproveCheckReq;
import com.retoc.oawx.domain.req.NotifyReq;
import com.retoc.oawx.domain.req.ProcessReq;
import com.retoc.oawx.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/approve")
@Api("确认模块接口")
@Slf4j
public class ApproveController {

    @Autowired
    LeaveService leaveService;

    @Autowired
    MeetingService meetingService;

    @Autowired
    UserService userService;

    @Autowired
    CarUseService carUseService;

    @Autowired
    CheckinService checkinService;

    @Autowired
    MaterialsService materialsService;

    @Autowired
    EvectionService evectionService;

    @Autowired
    OtService otService;

    @Autowired
    JWTUtil jwtUtil;

    @Value("${workflow.urla}")
    private String workflow;

    @PostMapping("/recNotify")
    @ApiOperation("自动接收工作流端审批信息")
    public R receiveNotify(@Valid @RequestBody NotifyReq req) {

        System.out.println("成功接收："+req.getInstanceId());
        System.out.println("成功接收："+req.getTypes());

        if (req.getTypes().equals("meeting")) {
            meetingService.approveMeetingByInstanceId(req.getInstanceId());
        } else if (req.getTypes().equals("leave")) {
            HashMap<String,Object> map=new HashMap<>();
            map.put("instanceId", req.getInstanceId());
            map.put("status",1);
//            请假单状态改为已审批
            leaveService.setStatus(map);
//            在签到表中添加请假记录
            HashMap<String,Object> param=new HashMap<>();
            param.put("userId",leaveService.searchLeaveByInstanceId(req.getInstanceId()).getCreatorId());
            param.put("startDate",leaveService.searchLeaveByInstanceId(req.getInstanceId()).getStart());
            param.put("endDate",leaveService.searchLeaveByInstanceId(req.getInstanceId()).getEnd());
            checkinService.leaveCheckin(param);
        }else if(req.getTypes().equals("car")) {
            carUseService.approveCarUseByInstanceId(req.getInstanceId());
        }else if(req.getTypes().equals("evection")) {
            evectionService.approveEvectionByInstanceId(req.getInstanceId());
        }else if(req.getTypes().equals("ot")) {
            otService.approveOtByInstanceId(req.getInstanceId());
        }
        return R.ok();
    }

    @PostMapping("/checkPendingApprove")
    @ApiOperation("查询当前所有未审批工作")
    public R checkPendingApprove(@RequestBody @Valid ApproveCheckReq req, @RequestHeader("token") String token){
        int type = req.getType();
        int userId = jwtUtil.getUserId(token);
//        String types=req.getTypes();
        //查询未审批的流程，发查询至工作流端处理
        if (type==0){
            JSONObject json = new JSONObject();
            json.set("checkerId", userId);
            json.set("type", "all");
            String url = workflow + "/approve/searchRequest";
            HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString())
                    .execute();
            if (resp.getStatus() == 200) {
                JSONObject json1 = JSONUtil.parseObj(resp.body());
//                JSONObject result = JSONUtil.parseObj(json1.getStr("result"));
                JSONArray result = JSONUtil.parseArray(json1.getStr("result"));
                List<HashMap> hashMaps = result.toList(HashMap.class);
//                ArrayList<HashMap<String,Object>> result =(ArrayList) json1.get("result");
                for (int i = hashMaps.size()-1; i >= 0 ; i--) {
                    HashMap r = hashMaps.get(i);
                    String instanceId =(String) r.get("instanceId");
                    String types = (String) r.get("types");
                    //如果类型为会议
                    if (types.equals("meeting")) {
                        Meeting meeting = meetingService.searchMeetingByInstanceId(instanceId);
                        if (meeting != null) {
                            r.put("date", meeting.getDate());
                            r.put("end", meeting.getEnd());
                            r.put("start", meeting.getStart());
                            DateTime endTime = DateUtil.parseTime(meeting.getEnd());
                            DateTime startTime = DateUtil.parseTime(meeting.getStart());
                            long between = endTime.between(startTime, DateUnit.HOUR);
                            System.out.println("between = " + between);
                            r.put("hours", between);
                            r.put("id", meeting.getId());
                            HashMap user = userService.searchUserInof(meeting.getCreatorId());
                            r.put("name",user.get("name"));
                            r.put("photo",user.get("photo"));
                            r.put("processType","meeting");
                            r.put("sameDept",meetingService.isSameDeptMeeting(meeting.getUuid()));
                            r.put("taskId", instanceId);
                            r.put("type", meeting.getType());
                            r.put("uuid", meeting.getUuid());
                            r.put("dept", user.get("dept"));
                        }
                    }
                    //如果类型为请假
                    else if (types.equals("leave")) {
                        Leave leave = leaveService.searchLeaveByInstanceId(instanceId);
                        if (leave != null){
                            r.put("date",leave.getStart());
                            r.put("hours", leave.getHour());
                            r.put("id", leave.getId());
                            r.put("processType","leave");
                            r.put("taskId", instanceId);
                            r.put("type", leave.getType());
                            r.put("uuid", leave.getUuid());
                            HashMap user = userService.searchUserInof(leave.getCreatorId());
                            r.put("name",user.get("name"));
                            r.put("photo",user.get("photo"));
                            r.put("dept", user.get("dept"));
                        }
                    }
                    //如果类型为用车申请
                    else if(types.equals("car")){
                        CarUse carUse=carUseService.selectCarUseByInstanceId(instanceId);
                        if (carUse==null){
                            hashMaps.remove(r);
                            continue;
                        }else {
//                            DateTime endTime = DateUtil.parseTime(carUse.getEndTime().toString());
//                            DateTime startTime = DateUtil.parseTime(carUse.getStartTime().toString());
                            long between = DateUtil.between(carUse.getStartTime(),carUse.getEndTime(),DateUnit.HOUR);

                            String date = DateUtil.format(carUse.getStartTime(),"yyyy-MM-dd");
                            ArrayList<HashMap> carMap = carUseService.selectCar();
                            r.put("carId", carUse.getCarId());
                            Materials car = materialsService.selectCarByid(carUse.getCarId());
                            r.put("carName", car.getName());
                            r.put("id", carUse.getId());
                            r.put("date",date);
                            r.put("processType","car");
                            r.put("driver",carUse.getDriver());
                            r.put("hours", between);
                            r.put("taskId", instanceId);
                            HashMap user = userService.searchUserInof(carUse.getCreaterId());
                            r.put("name",user.get("name"));
                            r.put("photo",user.get("photo"));
                            r.put("dept", user.get("dept"));
                        }
                    }
                    //如果类型为出差申请
                    else if (types.equals("evection")) {
                        Evection evection=evectionService.selectEvectionByInstanceId(instanceId);
                        if (evection==null){
                            hashMaps.remove(r);
                            continue;
                        }else {
//                            DateTime endTime = DateUtil.parseTime(carUse.getEndTime().toString());
//                            DateTime startTime = DateUtil.parseTime(carUse.getStartTime().toString());
                            long between = DateUtil.between(evection.getStartTime(),evection.getEndTime(),DateUnit.HOUR);

                            String date = DateUtil.format(evection.getStartTime(),"yyyy-MM-dd");
                            ArrayList<HashMap> carMap = carUseService.selectCar();
                            r.put("place", evection.getPlace());
                            r.put("id", evection.getId());
                            r.put("date",date);
                            r.put("taskId", instanceId);
                            r.put("processType","evection");
                            r.put("hours", between);
                            HashMap user = userService.searchUserInof(evection.getCreaterId());
                            r.put("name",user.get("name"));
                            r.put("photo",user.get("photo"));
                            r.put("dept", user.get("dept"));
                            r.put("reason",evection.getReason());
                        }
                    }
                    //加班申请
                    else if (types.equals("ot")) {
                        Ot ot=otService.selectOtByInstanceId(instanceId);
                        if (ot==null){
                            hashMaps.remove(r);
                            continue;
                        }else {
//                            DateTime endTime = DateUtil.parseTime(carUse.getEndTime().toString());
//                            DateTime startTime = DateUtil.parseTime(carUse.getStartTime().toString());
                            long between = DateUtil.between(ot.getStartTime(),ot.getEndTime(),DateUnit.HOUR);

                            String date = DateUtil.format(ot.getStartTime(),"yyyy-MM-dd");
                            r.put("id", ot.getId());
                            r.put("date",date);
                            r.put("startTime", ot.getStartTime());
                            r.put("endTime", ot.getEndTime());
                            r.put("taskId", instanceId);
                            r.put("processType","ot");
                            r.put("hours", between);
                            HashMap user = userService.searchUserInof(ot.getCreaterId());
                            r.put("name",user.get("name"));
                            r.put("photo",user.get("photo"));
                            r.put("dept", user.get("dept"));
                            r.put("reason", ot.getReason());
                        }
                    }
                }
                List<HashMap> resultMaps = new ArrayList<>();
                if (!req.getTypes().equals("all")){
                    for (HashMap res: hashMaps) {
                        String types = (String) res.get("types");
                        if (types.equals(req.getTypes())){
                            resultMaps.add(res);
                        }
                    }
                    return R.ok().put("result",resultMaps);
                }
                return R.ok().put("result",hashMaps);
            }
        }
        return R.ok();
    }

    @PostMapping("/processApprove")
    @ApiOperation("审批工作流")
    public R processApprove(@Valid @RequestBody ProcessReq req){

        JSONObject json = new JSONObject();

        json.set("instanceId", req.getInstanceId());
        json.set("approval", req.getApproval());
        json.set("reason", req.getReason());
        String url = workflow + "/approve/approval";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString())
                .execute();
        if (resp.getStatus() == 200) {
            JSONObject json1 = JSONUtil.parseObj(resp.body());
            return R.ok().put("result",json1);
        }
        return R.error("工作流链接失败");
    }

    @DeleteMapping("/deleteProcess")
    @ApiOperation("删除工作流")
    public R deleteProcess(@Valid @RequestBody ProcessReq req) {
        JSONObject json = new JSONObject();
        json.set("instanceId", req.getInstanceId());
        json.set("approval", req.getApproval());
        json.set("reason", req.getReason());
        String url = workflow + "/approve/DeleteProcessById";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString())
                .execute();
        if (resp.getStatus() == 200) {
            JSONObject json1 = JSONUtil.parseObj(resp.body());
            return R.ok().put("result",json1);
        }
        return R.error("工作流链接失败");
    }
}
